package com.feimt.web;


import com.feimt.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${feimt.path}")
    private String path;

    /*
    * 上传
    * */
    @PostMapping("/upload")
    public R upload(MultipartFile file){
        log.info("file:{}",file);
        /*tmp 文件 - copy 到 位置 D:/imgs/xxx.png  */
        /*1.获取文件夹路径 path*/
        /*2. 文件名处理*/  /*1111.png*/
        String originalFilename = file.getOriginalFilename();
        /*2.1 获取一个随机字符串当文件名*/
        String filename = UUID.randomUUID().toString();
        /*2.2 获取文件后缀名*/
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String sub = originalFilename.substring(lastIndexOf);
        /*2.3 字符串拼接    xxxxx.png*/
        filename += sub;

        /*3. 创建文件对象完成copy i/o*/
        /*3.1 获取 目标文件对象*/
        File file1 = new File(path + filename);
        /*3.2 文件copy*/
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*4. data = 文件名称*/
        return R.success(filename);
    }

    @GetMapping("/download")
    public R download(String name, HttpServletResponse response){
        log.info("name:{}",name);
        /*获取服务器上的图片的流 把流 返回*/

        try {
            /*1.获取服务器上的文件*/
            FileInputStream in = new FileInputStream(path + name);

            ServletOutputStream out = response.getOutputStream();
            /*2. 读写*/
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = in.read(bytes))!= -1){
                out.write(bytes,0,len);
                out.flush();
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success("ok");
    }
}
